package com.kscrm.web.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Objects;

import cn.hutool.core.date.DateUtil;
import com.kscrm.common.exception.ServiceException;
import com.kscrm.common.utils.SecurityUtils;
import com.kscrm.common.utils.StringUtils;
import com.kscrm.common.utils.bean.BeanValidators;
import com.kscrm.common.utils.uuid.IdUtils;
import com.kscrm.common.utils.uuid.UUID;
import com.kscrm.system.domain.SysConfig;
import com.kscrm.system.mapper.SysConfigMapper;
import com.kscrm.web.criteria.ClientCountCriteria;
import com.kscrm.web.domain.Client;
import com.kscrm.web.domain.ClientContact;
import com.kscrm.web.domain.ClientExpert;
import com.kscrm.web.domain.Expert;
import com.kscrm.web.dto.ClientImportDto;
import com.kscrm.web.mapper.ClientContactMapper;
import com.kscrm.web.mapper.ClientExpertMapper;
import com.kscrm.web.mapper.ClientMapper;
import com.kscrm.web.mapper.ExpertMapper;
import com.kscrm.web.service.IClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.Validator;

/**
 * 客户Service业务层处理
 *
 * @author Dhq
 * @date 2025-01-20
 */
@Service
public class ClientServiceImpl implements IClientService {
    @Autowired
    protected Validator validator;
    @Autowired
    private ClientMapper clientMapper;
    @Autowired
    private SysConfigMapper sysConfigMapper;
    @Autowired
    private ClientContactMapper clientContactMapper;
    @Autowired
    private ExpertMapper expertMapper;
    @Autowired
    private ClientExpertMapper clientExpertMapper;

    /**
     * 查询客户
     *
     * @param id 客户主键
     * @return 客户
     */
    @Override
    public Client selectClientById(Long id) {
        return clientMapper.selectClientById(id);
    }

    /**
     * 查询客户列表
     *
     * @param client 客户
     * @return 客户
     */
    @Override
    public List<Client> selectClientList(Client client) {
        return clientMapper.selectClientList(client);
    }

    /**
     * 新增客户
     *
     * @param client 客户
     * @return 结果
     */
    @Override
    public int insertClient(Client client) {
        // 设置有效期
        SysConfig config = sysConfigMapper.selectConfigById(100L);
        if (config == null) {
            throw new RuntimeException("系统配置不存在");
        }
        try {
            int day = Integer.parseInt(config.getConfigValue());
            client.setStartAt(new Date());
            client.setEndAt(DateUtil.offsetDay(new Date(), day));
        } catch (Exception e) {
            throw new RuntimeException("系统配置异常:" + e.getMessage());
        }
        if (SecurityUtils.hasRole("channel")) {
            client.setChannelId(SecurityUtils.getChannelId());
        }
        client.setUserId(SecurityUtils.getUserId());
        // 判断是否个人客户
        if(Objects.equals(client.getType(), "个人客户") && !client.getContactList().isEmpty()) {
            validatePersonalClient(client.getContactList().get(0).getPhone());
        }
        int row = clientMapper.insertClient(client);
        if (row == 0) {
            throw new RuntimeException("新增客户失败：该客户名称已被注册,请更换客户名称");
        }
        // 新增联系人
        if (client.getContactList() == null || client.getContactList().isEmpty()) {
            throw new RuntimeException("新增客户失败：请添加联系人");
        }
        for (ClientContact contact : client.getContactList()) {
            contact.setClientId(client.getId());
            clientContactMapper.insertClientContact(contact);
        }
        // 专家添加
        if (SecurityUtils.hasRole("teacher")) {
            Expert expert = expertMapper.selectExpertByUserId(SecurityUtils.getUserId());
            if (Objects.nonNull(expert)) {
                clientExpertMapper.insertClientExpert(
                        new ClientExpert()
                                .setExpertId(expert.getId())
                                .setClientId(client.getId())
                );
            }
        }
        return row;
    }


    /**
     * 验证个人客户的手机号不同
     * */
    private void validatePersonalClient(String phone) {
        Boolean isExists = clientContactMapper.selectClientContactIsExistsByPhone(phone);
        if (isExists) {
            throw new ServiceException("手机号已被注册");
        }
    }

    /**
     * 修改客户
     *
     * @param client 客户
     * @return 结果
     */
    @Override
    public int updateClient(Client client) {
        int row = clientMapper.updateClient(client);
        if (row == 0) {
            throw new RuntimeException("修改客户失败：该客户手机号已被注册");
        }
        // 修改联系人
        if (client.getContactList() == null || client.getContactList().isEmpty()) {
            throw new RuntimeException("修改客户失败：请添加联系人");
        }
        for (ClientContact contact : client.getContactList()) {
            clientContactMapper.updateClientContact(contact);
        }
        return row;
    }

    /**
     * 批量删除客户
     *
     * @param ids 需要删除的客户主键
     * @return 结果
     */
    @Override
    public int deleteClientByIds(Long[] ids) {
        return clientMapper.deleteClientByIds(ids);
    }

    /**
     * 删除客户信息
     *
     * @param id 客户主键
     * @return 结果
     */
    @Override
    public int deleteClientById(Long id) {
        return clientMapper.deleteClientById(id);
    }

    @Override
    public int selectClientCount(ClientCountCriteria criteria) {
        return clientMapper.selectClientCount(criteria);
    }


    @Override
    public String importClient(List<ClientImportDto> clientList) {
        // 设置有效期
        SysConfig config = sysConfigMapper.selectConfigById(100L);
        if (config == null) {
            throw new RuntimeException("系统配置不存在");
        }
        if (StringUtils.isNull(clientList) || clientList.isEmpty()) {
            throw new ServiceException("导入客户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        Long userId = SecurityUtils.getUserId();
        Long channelId = SecurityUtils.getChannelId();
        for (ClientImportDto client : clientList) {
            // 生成客户编号
            String serialNumber = IdUtils.fastUUID();
            try {
                // 验证是否存在这个客户 (个人客户 手机号验证,其他客户 名称验证)
                BeanValidators.validateWithException(validator, client);

                Client _client = new Client().setName(client.getName())
                        .setType(client.getType())
                        .setAddress(client.getAddress())
                        .setRemark(client.getRemark())
                        .setSerialNumber(serialNumber)
                        .setUserId(userId)
                        .setChannelId(channelId);
                try {
                    int day = Integer.parseInt(config.getConfigValue());
                    _client.setStartAt(new Date());
                    _client.setEndAt(DateUtil.offsetDay(new Date(), day));
                } catch (Exception e) {
                    throw new RuntimeException("系统配置异常:" + e.getMessage());
                }
                clientMapper.insertClient(_client);

                Long clientId = _client.getId();
                // 新增联系人
                clientContactMapper.insertClientContact(new ClientContact()
                        .setClientId(clientId)
                        .setName(client.getContactName())
                        .setPhone(client.getContactPhone())
                        .setJob(client.getJob())
                );
                successNum++;
                successMsg.append("<br/>" + successNum + "、客户 " + client.getName() + " 导入成功");
//                else
//                {
//                    failureNum++;
//                    failureMsg.append("<br/>" + failureNum + "、客户 " + client.getName() + " 导入失败");
//                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、客户 " + client.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
